package com.joe.framework.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Objects;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    private static final Logger logger = LoggerFactory.getLogger(MetaHandler.class);

    /**
     * 新增数据执行
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        /*SysUser userEntity = ShiroUtils.getSysUser();*/
        if (metaObject.hasSetter("createTime")){
            Object createTime = getFieldValByName("createTime",metaObject);
            if (Objects.nonNull(createTime)){
                setFieldValByName("createTime", createTime,metaObject);
            }else {
                setFieldValByName("createTime", new Date(),metaObject);
            }
        }
    }

    /**
     * 更新数据执行
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
       /* SysUser userEntity = ShiroUtils.getSysUser();*/
        if (metaObject.hasSetter("updateTime")){
            Object createTime = getFieldValByName("updateTime",metaObject);
            if (Objects.nonNull(createTime)){
                setFieldValByName("updateTime", createTime,metaObject);
            }else {
                setFieldValByName("updateTime", new Date(),metaObject);
            }
        }
    }
}
